<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" onclick="audio.play()" value="播放"/>
<input type="button" onclick="audio.pause()" value="暂停"/>
<canvas id="wrap" height="800" width="800"></canvas>
<script>
    /**@type {HTMLCanvasElement} */
    const wrap = document.getElementById("wrap");
    /**@type{CanvasRenderingContext2D }*/
    const cxt = wrap.getContext("2d");
    //获取API

    const AudioContext = AudioContext || webkitAudioContext;
    /**@type{AudioContext}*/
    const context = new AudioContext();
    //加载媒体

    const audio = new Audio('./music/HITA - 赤伶.mp3');
    //创建节点
    const source = context.createMediaElementSource(audio);
    const analyser = context.createAnalyser();
    //连接：source → analyser → destination
    source.connect(analyser);
    analyser.connect(context.destination);
    //创建数据
    const output = new Uint8Array(180);
    const du = 2;//角度
    const potInt = {x: 300, y: 300};//起始坐标
    const R = 200;//半径
    const W = 2;//宽
    (function drawSpectrum() {
        analyser.getByteFrequencyData(output);//获取频域数据

        cxt.clearRect(0, 0, wrap.width, wrap.height);
        //画线条
        let Rv;
        for (let i = 0; i < 180; i++) {
            const value = output[i] / 10;//<===获取数据
            cxt.beginPath();
            cxt.lineWidth = W;
            Rv = (R - value);
            cxt.moveTo((Math.sin((i * du) / 180 * Math.PI) * R + potInt.y), -Math.cos((i * du) / 180 * Math.PI) * R + potInt.x);
            cxt.lineTo((Math.sin((i * du) / 180 * Math.PI) * Rv + potInt.y), -Math.cos((i * du) / 180 * Math.PI) * Rv + potInt.x);
            cxt.stroke();
        }
        cxt.fill();
        //画一个空心小圆，将线条覆盖
        cxt.beginPath();
        cxt.lineWidth = 1;
        cxt.arc(300, 300, 200, 0, 2 * Math.PI, false);
        cxt.stroke();
        cxt.closePath();
        //请求下一帧
        requestAnimationFrame(drawSpectrum);
    })();
</script>

</body>
</html>
